/*
 * @Author: Gavin
 * @Date: 2018-09-07 12:55:39
 * @LastEditors: Gavin
 * @LastEditTime: 2018-09-07 15:43:05
 * @Description:
 */
let path = require('path')
let webpack = require('webpack')
let HtmlWebpackPlugin = require('html-webpack-plugin')
let HtmlWebpackHarddiskPlugin = require('html-webpack-harddisk-plugin')
let MiniCssExtractPlugin = require('mini-css-extract-plugin')
let CompressionWebpackPlugin = require('compression-webpack-plugin')
let BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin

let htmlMinifyOptions = require('../config/htmlminify')
let { SERVER_PATH, BUILD_PATH, ROOT_PATH } = require('../config/paths.conf')


const define = (isprod, target) => {
    let proc = {}

    return new webpack.DefinePlugin(proc)
}
const HtmlWebpack = () => new HtmlWebpackPlugin({
    filename: path.join(BUILD_PATH, 'web.html'), //生成的html存放路径，相对于 path
    template: path.join(SERVER_PATH, 'views', 'web.html'),
    inject: true,
    alwaysWriteToDisk: true,
    minify: htmlMinifyOptions
})
const MiniCssExtract = () => new MiniCssExtractPlugin({
    filename: '[name].[contenthash:7].css',
    chunkFilename: 'chunk.[contenthash:7].css'  // use contenthash *
})
const CompressionWebpack = () => new CompressionWebpackPlugin({
    filename: '[path].gz[query]',// 目标文件名
    algorithm: 'gzip',// 使用gzip压缩
    test: new RegExp(
        '\\.(js|css)$' // 压缩 js 与 css
    ),
    threshold: 10240,// 资源文件大于10240B=10kB时会被压缩
    minRatio: 0.8 // 最小压缩比达到0.8时才会被压缩
})
const BundleAnalyzer = () => new BundleAnalyzerPlugin({
    analyzerHost: '0.0.0.0'
})
module.exports = (isprod, target) => [
    define(isprod, target),
    HtmlWebpack(),
    MiniCssExtract(),
].concat(
    (!isprod) ?
        [
            // new HtmlWebpackHarddiskPlugin(),
            new webpack.HotModuleReplacementPlugin(),
        ] : [
            CompressionWebpack()
        ]
)

